<?php

namespace app\api\controller;

use app\api\model\WechatCardCode;
use app\api\model\WechatCard;
use think\Controller;

class Card extends Base
{
    protected $wechatCard;
    protected $beforeActionList = [
        'checkToken'=>['except'=>'list']
    ];

    protected function _initialize()
    {
        parent::_initialize();
    }

    //优惠券列表
    public function list()
    {
        //从微信服务器获取卡券列表
//        $cardList = session('card_list_'.$this->appletId);
//        $cardList = [];
//        if(empty($cardList)){
//            $this->wechatCard = new \app\mpbase\library\WechatCard();
//            $cardList = $this->wechatCard->cardList();
//            session('card_list_'.$this->appletId,$cardList);
//        }
//        $res['data'] = $cardList;
//        return self::apiResp($res);

        $row = input('row', 10);
        $page = input('page', 1);
        $data = WechatCard::getList([], $page, $row);
        return self::apiResp($data);
    }

    public function activateCard()
    {
        $this->wechatCard = new \app\mpbase\library\WechatCard();
        $res = $this->wechatCard->addCardExt();
    }

    //生成领取卡券的 cardExt
    public function card_ext()
    {
        if(input('card_id')=='')
            $res = ['_code'=>400,'msg'=>'card_id不能为空'];
        else{
            $this->wechatCard = new \app\mpbase\library\WechatCard();
            $res = $this->wechatCard->addCardExt();
        }
        return self::apiResp($res);
    }

    //保存领取的卡券Code、CardId
    public function save_code()
    {
        $res = WechatCardCode::saveCode(
            get_api_applet_id(),
            $this->userId,
            input('post.'));
        return self::apiResp($res);
    }

    //检查卡券Code 并同步 状态
    public function check_code()
    {
        $decryptCode = input('post.decrypt_code');
        $this->wechatCard = new \app\mpbase\library\WechatCard();
        $res = $this->wechatCard->checkCode($decryptCode);
        if($res['errcode'] == 0 && $res['errmsg'] == 'ok'
            && !$res['can_consume'] ){
            WechatCardCode::setState($decryptCode,$res['user_card_status']);
        }
        return self::apiResp($res);
    }

    //保存领取的卡券Code、CardId
    public function delete_code()
    {
        $decryptCode = input('post.decrypt_code');
        $code = WechatCardCode::get(['decrypt_code'=>$decryptCode]);
        if(!$code){
            $res = ['_code'=>'400','msg'=>'该卡券不存在'];
        }else{
            $res = WechatCardCode::deleteCode($decryptCode,true);
        }
        return self::apiResp($res);
    }

    //优惠券列表
    public function my_list()
    {
        $row = input('row', 10);
        $page = input('page', 1);
        $data = WechatCard::getListByUser($this->userId, $page, $row);
        return self::apiResp($data);
    }
}
